package com.demo.nfcdemo.simulate;

import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.util.Log;

import com.demo.nfcdemo.utils.ThreadUtils;
import com.demo.nfcdemo.v.CActivity;

import java.util.Arrays;

/**
 * @author ljb
 * @des
 * @date 2020/5/19
 */
public class CardSimulateCallback implements NfcAdapter.ReaderCallback {
    private static final String TAG = "CardSimulateCallback";
    private static final String SAMPLE_LOYALTY_CARD_AID = "F222222223";
    private static final String SELECT_APDU_HEADER = "00A40400";
    private static final byte[] SELECT_OK_SW = {(byte) 0x90, (byte) 0x00};

    private CActivity v;

    public CardSimulateCallback(CActivity activity) {
        v = activity;
    }

    @Override
    public void onTagDiscovered(Tag tag) {
        IsoDep isoDep = IsoDep.get(tag);
        if (isoDep != null) {
            try {
                isoDep.connect();
                byte[] command = BuildSelectApdu(SAMPLE_LOYALTY_CARD_AID);
                byte[] result = isoDep.transceive(command);
                int resultLength = result.length;
                byte[] statusWord = {result[resultLength - 2], result[resultLength - 1]};
                byte[] payload = Arrays.copyOf(result, resultLength - 2);
                if (Arrays.equals(SELECT_OK_SW, statusWord)) {

                    //读取仿真卡中的数据
                    String data = new String(payload, "UTF-8");
                    ThreadUtils.runOnUiThread(() -> {
                        v.showDialog("读取标签内容为:\n" +data);
                    });
                }
            } catch (Exception e) {
                Log.e(TAG, "onTagDiscovered: " + e);
            }
        }
    }

    public static byte[] BuildSelectApdu(String aid) {
        return HexStringToByteArray(SELECT_APDU_HEADER + String.format("%02X", aid.length() / 2) + aid);
    }

    public static byte[] HexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}
